import { Component, ViewChild } from '@angular/core';
import { Platform, ToastController, Nav, App, AlertController } from 'ionic-angular';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AppVersion } from '@ionic-native/app-version';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FileOpener } from '@ionic-native/file-opener';
import { File } from '@ionic-native/file';
import { AndroidPermissions } from '@ionic-native/android-permissions';

import { TabsPage } from '../pages/tabs/tabs';
import { LoginPage } from '../pages/login/login';
import { SecurityService } from '../app/core/security/SecurityService';
import { BaseService } from '../app/core/data/BaseService';
import { DataService } from '../app/core/data/DataService';

@Component({
  template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})

export class MyApp {

  @ViewChild('myNav') nav: Nav;//声明根组件(<ion-nav #myNav [root]="rootPage">)
  public rootPage:any = TabsPage;
  //用于判断返回键是否触发
  private backButtonPressed: boolean = false;

  constructor(
    private appCtrl: App,
    private platform: Platform,
    private statusBar: StatusBar,
    private splashScreen: SplashScreen,
    private securityService:SecurityService,
    private toastCtrl: ToastController,
    private appVersion: AppVersion,
    private alertCtrl: AlertController,
    private fileOpener: FileOpener,
    public baseService:BaseService,
    public dataService:DataService,
    private file: File,
    private transfer: Transfer,
    private androidPermissions: AndroidPermissions) {

    platform.ready().then(() => {
      /*储存版本信息及判断存储路径开始*/
      // 读取所用的平台
      //获取当前平台信息
      var order={};
      order["numversion"]=1;
      this.dataService.getEntitys("appupdatenet",null,null,order,1,1).subscribe((data)=>{
          if(data!=null && data.length>0){
            var serverNumVersion=data[0]["numversion"];
            this.appVersion.getVersionNumber().then(version=>{
              //当前app版本号  data，存储该版本号
              var ver=version.replace(".","").replace(".","");
              var numVersion=parseInt(ver);
              console.log("version=====本机>>>"+numVersion+"====>>服务器"+serverNumVersion); 
              if(numVersion<serverNumVersion){
                this.alertCtrl.create({
                  title: '升级',
                  subTitle: '发现新版本,是否立即升级？',
                  buttons: [{text: '取消'},
                    {
                      text: '确定',
                      handler: () => {
                        let fj:string=data[0]["url"];
                        if(fj!=null){
                          let fjs:string[]=fj.split(":");
                          //var url=this.baseService.baseUrl+"/file/plupload/download?bucket="+fjs[0]+"&key="+fjs[1]+"&name="+fjs[2];
                          // const browser = this.inAppBrowser.create(this.baseService.hostUrl+"/app/"+fjs[2]);
                          // browser.show();
                          var list = [
                            androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE,
                            androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE,
                            androidPermissions.PERMISSION.INTERNET,
                            //可以写多个权限
                          ];
                          this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then((s)=>{
                            if (!s.hasPermission) {
                              //没有权限
                              //app申请写入权限
                              this.androidPermissions.requestPermissions(list).then((st)=>{
                                if (st.hasPermission) {
                                  //申请成功
                                  this.downloadApp(this.baseService.hostUrl+"/app/"+fjs[2]);
                                }
                                else {
                                  //申请失败
                                  let temp = this.alertCtrl.create({
                                    title: '系统提示',
                                    subTitle: '权限不足，从浏览器下载安装包!',
                                    buttons: [{
                                      text:"确定",
                                      handler: ()=>{
                                        window.open(this.baseService.hostUrl+"/app/"+fjs[2],"_system");
                                      }
                                    }]
                                  });
                                  temp.present();
                                }
                              });
                            } else {
                              this.downloadApp(this.baseService.hostUrl+"/app/"+fjs[2]);
                            }
                          });
                          
                          //this.getPrmissions();
                          //this.downloadApp(this.baseService.hostUrl+"/app/"+fjs[2]);
                        }else{
                          let temp = this.alertCtrl.create({
                            title: '系统提示',
                            subTitle: '未找到安装包，请联系管理员!',
                            buttons: ['确定']
                          });
                          temp.present();
                        }
                      }
                    }
                  ]
                }).present();
              }
            }, error => console.error(error => {
              //获取当前版本号失败进行的操作
            }));
          }
      });

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
      this.statusBar.overlaysWebView(true);
     // statusBar.backgroundColorByHexString('#5276b2');
     try{
      let username=window.localStorage.getItem('bhqoa_username');
      let password=window.localStorage.getItem('bhqoa_password');
      let initLogin=window.localStorage.getItem('bhqoa_initLogin');
 
      if(initLogin=="true" && username!=null && username!="" && password!=null && password!="" ){
       this.securityService.showMessage=false;
       this.securityService.login(username, password, (data)=>{
         this.rootPage=TabsPage;
       });
      }
     }catch(e){
     }
    });

    this.registerBackButtonAction();
  }

  downloadApp(url) {
    let alert = this.alertCtrl.create({
      title: '下载进度：0%',
      enableBackdropDismiss: false,
      buttons: ['后台下载']
    });
    alert.present();

    const fileTransfer: TransferObject = this.transfer.create();
    const apk = this.file.externalRootDirectory + '/maolanoa/maolanoa.apk'; //apk保存的目录
    fileTransfer.download(encodeURI(url), apk).then(() => {
      this.fileOpener.open(apk, 'application/vnd.android.package-archive').then(() =>{
        console.log('File is opened')
      }).catch(e => {
        console.log('Error openening file', e)
      });
    });

    fileTransfer.onProgress((event: ProgressEvent) => {
      let num = Math.floor(event.loaded / event.total * 100);
      if (num === 100) {
        alert.dismiss();
      } else {
        let title = document.getElementsByClassName('alert-title')[0];
        title && (title.innerHTML = '下载进度：' + num + '%');
      }
    });
  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      // 控制modal、系统自带提示框
      let overlay = this.appCtrl._appRoot._overlayPortal.getActive() || this.appCtrl._appRoot._modalPortal.getActive();
      if(overlay) {
        overlay.dismiss();
        return;
      }

      let activeVC = this.nav.getActive();
      let page = activeVC.instance;
      if(page.tabs){
        let activeNav = page.tabs.getSelected();
        if(activeNav.canGoBack()){
          return activeNav.pop();
        }else{
          return this.showExit();
        }
      }

      //如果是登录页面的返回事件，直接退出系统
      if(page instanceof LoginPage){
        return this.showExit();
      }
      //剩余的情况全部使用全局路由进行操作
      this.appCtrl.getActiveNav().pop();
    }, 1);
  }

  //双击退出提示框
  showExit() {
    //当触发标志为true时，即2秒内双击返回按键则退出APP
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      this.toastCtrl.create({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'center'
      }).present();
      this.backButtonPressed = true;
      //2秒内没有再次点击返回则将触发标志标记为false
      setTimeout(() => this.backButtonPressed = false, 2000);
    }
  }
}